package leetcodev1.链表;

public class LeetCode24 {

    public ListNode swapPairs(ListNode head) {
        if (head == null) {
            return null;
        }

        ListNode virtualNode = new ListNode(-1, head), pre = virtualNode, first = head;
        while (first != null) {
            if (first.next == null) {
                break;
            }

            ListNode second = first.next;
            ListNode last = second.next;

            pre.next = second;
            second.next = first;
            first.next = last;

            pre = pre.next.next;
            first = first.next;
        }
        return virtualNode.next;
    }
}

class Answer24{

    //1.递归（链表其实也可以递归）
    //巧妙
    public ListNode swapPairs(ListNode head) {
        //终止条件：没有节点，或只有节点
        if (head == null || head.next == null) {
            return head;
        }
        ListNode newHead = head.next;
        head.next = swapPairs(newHead.next);//交换位置（后面的位置也需要交换）
        newHead.next = head;//交换位置
        return newHead;
    }

    //2.迭代 视角是前一个 交换后两个 牛皮
    public ListNode swapPairs1(ListNode head) {
        ListNode dummyHead = new ListNode(0);
        dummyHead.next = head;
        ListNode temp = dummyHead;
        while (temp.next != null && temp.next.next != null) {
            ListNode node1 = temp.next;
            ListNode node2 = temp.next.next;
            temp.next = node2;
            node1.next = node2.next;
            node2.next = node1;
            temp = node1;
        }
        return dummyHead.next;
    }

}
